package com.noah.bee.admin.web.controller;

import com.noah.bee.admin.domain.User;
import com.noah.bee.admin.service.UserService;
import com.noah.bee.admin.servlet.constants.GlobalConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;

/**
 * @author wuzhen
 * @since 16/12/19 15:32
 */

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login")
    public ModelAndView login(String userName, String password, boolean submit, HttpSession session) throws NoSuchAlgorithmException {
        ModelAndView mal = new ModelAndView();
        if (submit) { // 真正的登陆动作
            // login magic
            User user = userService.getUser(userName, password);
            if (null == user) {
                mal.setViewName("login");
                mal.addObject("showNotice", true);
                mal.addObject("notice", "用户名或者密码错误");

            } else {
                // 写session
                session.setAttribute(GlobalConstants.USER_SESSION, user);
                // 获取登录成功后需要跳转的URI
                Object preURI = session.getAttribute(GlobalConstants.PRE_REQUEST_URI);
                String uri = null == preURI ? "/" : preURI.toString();
                session.removeAttribute(GlobalConstants.PRE_REQUEST_URI);

                mal.setView(new RedirectView(uri));
            }

        } else { // 渲染登录界面
            mal.setViewName("login");
            mal.addObject("showNotice", false);
        }
        return mal;
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) throws IOException {
        session.removeAttribute(GlobalConstants.USER_SESSION);
        return "redirect:login";
    }

}
